CREATE OR REPLACE FUNCTION get_stores_by_monthly_profit_and_revenue_growth()
RETURNS TABLE (
    store_id INT,
    store_name TEXT,
    month_and_year TEXT,
    monthly_profit NUMERIC,
    previous_month_revenue NUMERIC,
    current_month_revenue NUMERIC,
    revenue_growth NUMERIC
)
LANGUAGE plpgsql
AS $$
BEGIN
    RETURN QUERY
    WITH monthly_revenue AS (
        SELECT
            s.store_id,
            s.name AS store_name,
            DATE_TRUNC('month', o.last_modified_date) AS month_date,
            SUM(
                p.price
                * o.quantity
                * (1 - COALESCE(o.discount, 0) / 100.0)
            ) AS revenue
        FROM store s
        JOIN sells se
            ON s.store_id = se.store_id
        JOIN product p
            ON se.code = p.code
        JOIN includes i
            ON p.code = i.code
        JOIN "order" o
            ON i.order_num = o.order_num
        GROUP BY
            s.store_id,
            s.name,
            DATE_TRUNC('month', o.last_modified_date)
    ),
    revenue_with_previous AS (
        SELECT
            store_id,
            store_name,
            month_date,
            revenue,
            LAG(revenue) OVER (
                PARTITION BY store_id
                ORDER BY month_date
            ) AS previous_month_revenue
        FROM monthly_revenue
    )
    SELECT
        store_id,
        store_name,
        TO_CHAR(month_date, 'YYYY-MM') AS month_and_year,
        revenue AS monthly_profit,
        COALESCE(previous_month_revenue, 0) AS previous_month_revenue,
        revenue AS current_month_revenue,
        revenue - COALESCE(previous_month_revenue, 0) AS revenue_growth
    FROM revenue_with_previous
    ORDER BY
        monthly_profit DESC,
        revenue_growth DESC;
END;
$$;